package im

import (
    "fmt"
	"encoding/json"
	"dhfshop/controllers/base"
	"thirdpaysdk/api/yabandpay"
	"dhfshop/domain/im"
	"github.com/astaxie/beego"
	"dhfshop/domain/pay"
	"dhfshop/service/redisgo"
)

type YabandNotifyController struct {
	base.BaseController
}

func (this *YabandNotifyController) YabandPayNotify() {
	notifyData := this.Ctx.Input.RequestBody
	beego.Debug("YabandPayNotify notifyData:", string(notifyData))
	//
	merchantId := this.GetString("merchant_id")
	var response yabandpay.YaNotifyMsg
	err := yabandpay.ParseYabandNotify(notifyData, &response)
	if err != nil {
		beego.Debug("ParseYabandNotify:", err.Error())
		return
	}
	if response.NotifyData.State == "expired" || response.NotifyData.State == "processing" {
	    this.Ctx.WriteString("ok")
		return
	}
	var payInfoCache *paylayer.PayInfoCache = new(paylayer.PayInfoCache)
	cacheKey := "payorder_" + response.NotifyData.OrderId
	redisconn := redisgo.GetInstance()
	if cacheValue, err := redisconn.GetString(cacheKey); err == nil && len(cacheValue) > 5  {
	    //beego.Debug("cache pay info:", cacheValue)
		if err = json.Unmarshal([]byte(cacheValue), payInfoCache); err == nil {
			
		}
	}else{
	    beego.Debug("cache pay info err:", err.Error())
		return 
	}
	rspMap, err := yabandpay.YabandNotify(notifyData,payInfoCache.AppKey,response)
	if err != nil {
	    beego.Debug("YabandNotify:", err.Error())
		return
	}
	reqMap := make(map[string]string)
	for k, v := range rspMap {
		reqMap[k] = fmt.Sprintf("%v", v)
	}
	reqMap["merchant_id"] = merchantId
	reqMap["LocalKind"] = "YABAND_PAY_NOTIFY"
	reqMap["attach"] = payInfoCache.OrderKind
	imlayer.PushMsgSvrIns.PushDao <- &reqMap
	this.Ctx.WriteString("ok")
	return
}
